package com.arcvideo.acsconnect.ui;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.arcvideo.acsconnect.app.AcsConnectApplication;
import com.arcvideo.acsconnect.app.GlobalConstant;
import com.arcvideo.acsconnect.bean.MessageBean;
import com.arcvideo.acsconnect.helper.MessageHelper;
import com.arcvideo.acsconnect.rest.model.UpgradeResultBean;
import com.arcvideo.acsconnect.rest.model.UserBean;
import com.arcvideo.acsconnect.ui.presenter.MainPresenter;
import com.arcvideo.acsconnect.ui.view.MainView;
import com.arcvideo.acsconnect.widget.AppDownloadDialog;
import com.arcvideo.acsconnect.widget.FitWidthImageView;
import com.arcvideo.acsconnect.widget.InviteDialog;
import com.arcvideo.acsconnect.widget.UpgradeDialog;
import com.arcvideo.acsconnect.widget.UserChangeDialog;
import com.arcvideo.arcrtcsdk.ArcRtcSDK;
import com.arcvideo.arcrtcsdk.listener.ArcRtcMessageListener;
import com.arcvideo.rtcmessage.model.RtcClientModel;
import com.arcvideo.rtcmessage.utils.LogUtil;
import com.arcvideo.rtcmessage.utils.NetworkUtil;
import com.arcvideo.tyingyitonginhouse.BuildConfig;
import com.arcvideo.tyingyitonginhouse.R;
import com.bumptech.glide.Glide;
import com.framework.core.mvp.TitlePresenterActivity;
import com.framework.core.utils.ToastUtil;
import com.framework.core.widget.CircleImageView;
import com.google.gson.Gson;

import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * @author shenmengchao
 * @version 1.0.0
 * @date 2017/10/17
 * @description 成员变量和成员函数放置顺序规则
 * 1.public static 的 成员变量
 * 2.private static 的 成员变量
 * 3.public 的成员变量（这个一般比较少）
 * 4.private 的成员变量
 * 5.public static 的函数
 * 6.public 的函数, 这里面调用了private的函数，就直接跟在调用者后面
 */

public class MainActivity extends TitlePresenterActivity<MainPresenter> implements
        MainView, View.OnFocusChangeListener, ArcRtcMessageListener {

    public final static String LAUNCH_FROM_BOOT = "LAUNCH_FROM_BOOT";
    private final static String TAG = MainActivity.class.getSimpleName();

    @BindView(R.id.iv_main_top)
    FitWidthImageView mFitWidthImageView;
    @BindView(R.id.iv_video)
    ImageView mIvVideo;
    @BindView(R.id.iv_order)
    ImageView mIvOrder;
    @BindView(R.id.iv_doctor)
    ImageView mIvDoctor;
    @BindView(R.id.iv_health)
    ImageView mIvHealth;
    @BindView(R.id.iv_activity)
    ImageView mIvActivity;
    @BindView(R.id.iv_avatar)
    CircleImageView mIvAvatar;
    @BindView(R.id.tv_name_and_account)
    TextView mTvNameAndAccount;
    @BindView(R.id.tv_age_and_sex)
    TextView mTvAgeAndSex;
    @BindView(R.id.iv_des)
    ImageView mIvDes;
    @BindView(R.id.iv_app_download_btn)
    ImageView mIvAppDownloadBtn;

    MainPresenter mMainPresenter = new MainPresenter();

    private InviteDialog mInviteDialog;
    private ArcRtcSDK mArcRtcSdk;
    private UserChangeDialog mUserChangeDialog;
    private UpgradeDialog mUpgradeDialog;
    private boolean mLaunchFromBoot;
    private boolean mIsStartHealth;

    public static void launchFromBoot(Context context) {
        Intent loginIntent = new Intent(context, MainActivity.class);
        loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        loginIntent.putExtra(LAUNCH_FROM_BOOT, true);
        context.startActivity(loginIntent);
    }

    public static void launch(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);
    }

    public void changeUser(int index) {
        mMainPresenter.logoutAndLoginOther(index);
    }

    @Override
    public void initActivity(View view) {
        super.initActivity(view);
        showContent();
        dismissToolbar();
        LogUtil.d(TAG, "initActivity taskId: " + getTaskId());
        initArcRtcSDK();
        initView();
        initEvent();
        init();
    }

    private void initArcRtcSDK() {
        if (null == mArcRtcSdk) {
            mArcRtcSdk = ArcRtcSDK.create(this);
        }
        initArcRtcSdkParams();
        mArcRtcSdk.enableLog(true);
        mArcRtcSdk.prepareIM();
        mArcRtcSdk.setArcRtcMessageListener(this);
    }

    private void initArcRtcSdkParams() {
        if (null != mArcRtcSdk) {
            int customerId = GlobalConstant.IM_CUSTOMER_ID;
            String imAddress = GlobalConstant.IM_ADDRESS;
            String orgId = GlobalConstant.IM_ORG_ID;
            mArcRtcSdk.setValidateParams(GlobalConstant.ACCESS_KEY, GlobalConstant.SECRET, GlobalConstant.APP_KEY)
                    .setProductId(GlobalConstant.PRODUCT_ID)
                    .setAccountInfo(customerId, orgId)
                    .setAddress(imAddress)
                    .setMaxSessionLength(GlobalConstant.MAX_SESSION_LENGTH);
        }
    }

    /**
     * 一般用于对布局的初始化，比如设置TextView ImageView等
     */
    private void initView() {
        mFitWidthImageView.setWindowWidth(getWindowManager().getDefaultDisplay().getWidth());
    }

    /**
     * 一般用于点击事件的设置，比如OnClickListener  OnFocusChangeListener等
     */
    private void initEvent() {
        mIvVideo.setOnFocusChangeListener(this);
        mIvOrder.setOnFocusChangeListener(this);
        mIvDoctor.setOnFocusChangeListener(this);
        mIvHealth.setOnFocusChangeListener(this);
        mIvActivity.setOnFocusChangeListener(this);
        mIvAppDownloadBtn.setOnFocusChangeListener(this);
    }

    /**
     * 其他的初始化，比如进入页面的接口调用等，可以在这里执行
     */
    private void init() {
        mIvVideo.setFocusable(true);
        mIvOrder.setFocusable(true);
        mIvDoctor.setFocusable(true);
        mIvHealth.setFocusable(true);
        mIvActivity.setFocusable(true);
        mIvVideo.requestFocus();

        mMainPresenter.getAccountsByStbId(this);
        //如果是通过开机自启启动的，需要启动APP，但是启动之后，需要推到后台，只需要能接受消息后唤醒即可
        mLaunchFromBoot = getIntent().getBooleanExtra(LAUNCH_FROM_BOOT, false);
        if (mLaunchFromBoot) {
            mLaunchFromBoot = false;
            toHomePage();
        }
    }

    /**
     * 这个代码的作用类似于点击HOME按钮，回到主页，把APP置于后台，APP本身不退出
     */
    private void toHomePage() {
//        ToastUtil.showToast("返回主页了。。。。");
        LogUtil.d(TAG, "toHomePage()");
        moveTaskToBack(false);


//        Intent intent = new Intent(Intent.ACTION_MAIN);
//        intent.addCategory(Intent.CATEGORY_HOME);
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        startActivity(intent);
    }

    @Override
    public int inflateContentView() {
        return R.layout.activity_main;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_ENTER:     //确定键enter
            case KeyEvent.KEYCODE_DPAD_CENTER:
                Log.d(TAG, "enter--->");
                if (mIvAppDownloadBtn.hasFocus()) {
                    showAppDownloadDialog();
                    return super.onKeyDown(keyCode, event);
                }
                if (mIvVideo.hasFocus()) {
                    UserBean userBean = AcsConnectApplication.sNurseList.get(0);
                    if (checkParamWhenCreateSession(userBean.getId())) {
                        startLiveActivityWithCreateSession(userBean);
                    }
                    return super.onKeyDown(keyCode, event);
                }
                if (mIvOrder.hasFocus()) {
                    UserBean userBean = AcsConnectApplication.sNurseList.get(1);
                    if (checkParamWhenCreateSession(userBean.getId())) {
                        startLiveActivityWithCreateSession(userBean);
                    }
                    return super.onKeyDown(keyCode, event);
                }
                if (mIvDoctor.hasFocus()) {
//                    showUpgradeDialog();
                    return super.onKeyDown(keyCode, event);
                }
                if (mIvHealth.hasFocus()) {
                    //非展厅环境需要跳转到健康学堂
                    if (!"hall".equals(BuildConfig.BUILD_TYPE)) {
                        jumpToHealthPage();
                        mIsStartHealth = true;
                    }
                    return super.onKeyDown(keyCode, event);
                }
                if (mIvActivity.hasFocus()) {
                    mMainPresenter.getAccountsByStbId(this);
                    return super.onKeyDown(keyCode, event);
                }
                break;
            case KeyEvent.KEYCODE_DPAD_LEFT:
                Log.d(TAG, "left");
                if (mIvVideo.hasFocus()) {
                    showUserChangeDialog();
                }
                break;
            case KeyEvent.KEYCODE_DPAD_UP:
                Log.d(TAG, "up");
                break;
            case KeyEvent.KEYCODE_DPAD_RIGHT:
                Log.d(TAG, "right");
                break;
            case KeyEvent.KEYCODE_DPAD_DOWN:
                Log.d(TAG, "down");
                break;
            case KeyEvent.KEYCODE_VOLUME_UP:
                Log.d(TAG, "KEYCODE_VOLUME_UP");
                break;
            default:
                break;
        }

        return super.onKeyDown(keyCode, event);
    }

    private void jumpToHealthPage() {
        try {
            Intent intent = new Intent();
            intent.setAction("wasu.intent.action.bs");
            intent.putExtra("param",
                    "http://utc-hotel.hzdtv.tv/template_hotel/hotel_ysbj/index.html");
            intent.putExtra("scale", 100);
            this.startActivity(intent);
        } catch (Exception e) {
            Log.e(TAG, "jump to health exception!!!" + e.getMessage());
        }
    }

    private void showUserChangeDialog() {
        mUserChangeDialog = new UserChangeDialog(this);
        mUserChangeDialog.show();
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        switch (v.getId()) {
            case R.id.iv_app_download_btn:
                if (hasFocus) {
                    mIvAppDownloadBtn.setImageResource(R.mipmap.ic_app_download_checked);
                } else {
                    mIvAppDownloadBtn.setImageResource(R.mipmap.ic_app_download);
                }
                break;
            case R.id.iv_video:
                if (hasFocus) {
                    mIvVideo.setImageResource(R.mipmap.ic_main_video_checked);
                    mIvDes.setImageResource(R.mipmap.ic_main_des_1);
                } else {
                    mIvVideo.setImageResource(R.mipmap.ic_main_video);
                }
                break;
            case R.id.iv_order:
                if (hasFocus) {
                    mIvOrder.setImageResource(R.mipmap.ic_main_order_checked);
                    mIvDes.setImageResource(R.mipmap.ic_main_des_2);
                } else {
                    mIvOrder.setImageResource(R.mipmap.ic_main_order);
                }
                break;
            case R.id.iv_doctor:
                if (hasFocus) {
                    mIvDoctor.setImageResource(R.mipmap.ic_main_doctor_checked);
                    mIvDes.setImageResource(R.mipmap.ic_main_des_3);
                } else {
                    mIvDoctor.setImageResource(R.mipmap.ic_main_doctor);
                }
                break;
            case R.id.iv_health:
                if (hasFocus) {
                    mIvHealth.setImageResource(R.mipmap.ic_main_healthy_checked);
                    mIvDes.setImageResource(R.mipmap.ic_main_des_4);
                } else {
                    mIvHealth.setImageResource(R.mipmap.ic_main_healthy);
                }
                break;
            case R.id.iv_activity:
                if (hasFocus) {
                    mIvActivity.setImageResource(R.mipmap.ic_main_active_checked);
                    mIvDes.setImageResource(R.mipmap.ic_main_des_5);
                } else {
                    mIvActivity.setImageResource(R.mipmap.ic_main_active);
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogUtil.d(TAG, "MainActivity onDestroy");
    }

    @Override
    public MainPresenter getPresenter() {
        return mMainPresenter;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (null != mArcRtcSdk) {
            mArcRtcSdk.setArcRtcMessageListener(this);
        }
    }

    private void initUserInfo(UserBean userBean) {
        LogUtil.d(TAG, "initUserInfo() " + userBean);
        if (null != userBean) {
            Glide.with(this).load(userBean.getHeadPicUrl()).into(mIvAvatar);
            mTvNameAndAccount.setText(userBean.getName() + " | " + userBean.getAccount());
            mTvAgeAndSex.setText(userBean.getAge() + "岁 " + userBean.getSex());
        }
    }

    private void showAppDownloadDialog() {
        AppDownloadDialog downloadDialog = new AppDownloadDialog(this);
        downloadDialog.show();
    }

    /**
     * @param userId 传入需要关闭dialog的userId，需要对比后才会关闭对应的dialog
     * @return true 如果需要关闭dialog return true
     * 如果不需要关闭dialog，就return false
     */
    private boolean dismissInviteDialog(String userId) {
        if (null != mInviteDialog && mInviteDialog.isShowing() && userId.equals(mInviteDialog.getUserId())) {
            mInviteDialog.dismiss();
            return true;
        }
        return false;
    }

    private void showInviteDialog(final MessageBean messageBean) {
        //如果被邀请弹框出现时，又有人来邀请，直接拒绝。
        if (null != mInviteDialog && mInviteDialog.isShowing()) {
            MessageHelper.sendReplyMessage(messageBean.getId(), MessageBean.RESULT_REJECT, messageBean.getSessionid() + "");
            return;
        }
        mInviteDialog = new InviteDialog(MainActivity.this, messageBean);
        mInviteDialog.setOnConfirmListener(new InviteDialog.OnConfirmListener() {

            @Override
            public void onConfirm(String id) {
                startLiveActivityWithJoinSession(messageBean.getSessionid());
                MessageHelper.sendReplyMessage(id, MessageBean.RESULT_ACCEPT, messageBean.getSessionid());
            }

            @Override
            public void onReject(String id) {
                MessageHelper.sendReplyMessage(id, MessageBean.RESULT_REJECT, messageBean.getSessionid());
            }
        });
        mInviteDialog.show();
    }

    private void startLiveActivityWithCreateSession(UserBean userBean) {
        LiveActivity.launchCreate(this,
                userBean.getId(), userBean.getHeadPicUrl(), userBean.getName());
    }

    private void startLiveActivityWithJoinSession(String sessionId) {
        LiveActivity.launchJoin(this, Integer.parseInt(sessionId));
    }

    private boolean checkParamWhenCreateSession(String userId) {
        if (!NetworkUtil.isNetworkConnected(this)) {
            ToastUtil.showToast("网络不可用，请检查网络后重试");
            return false;
        }
        if (!isUserOnline(userId)) {
            ToastUtil.showToast("护士不在线，请稍后再试");
            return false;
        }
        return true;
    }

    private boolean isUserOnline(String userId) {
        Map<String, RtcClientModel> map = mArcRtcSdk.getClientMap();
        if (null != map && map.size() > 0 && map.containsKey(userId)) {
            return true;
        }
        return false;
    }

    @Override
    public void onGetAccountsByStbIdSuccess(List<UserBean> list) {
        UserBean userBean = AcsConnectApplication.getCurrentUserBean();
        mMainPresenter.login(userBean.getAccount(), userBean.getPassword());
    }

    @Override
    public void onLoginSuccess(UserBean userBean) {
        Log.d(TAG, "onLoginSuccess() " + userBean);
        ToastUtil.showToast("登录成功");
        mMainPresenter.getNurseAccounts();
        reopenIm(userBean);
        initUserInfo(userBean);
        mMainPresenter.checkNewVersion(this);
    }

    @Override
    public void onLogoutAndLoginOtherSuccess(UserBean userBean) {
        Log.d(TAG, "onLogoutAndLoginOtherSuccess");
        ToastUtil.showToast("账户切换成功");
        reopenIm(userBean);
        initUserInfo(userBean);
    }

    private void reopenIm(UserBean userBean) {
        if (null != mArcRtcSdk) {
            mArcRtcSdk.setUserInfo(userBean.getId(), userBean.getName(), userBean.getHeadPicUrl());
            mArcRtcSdk.reopenIM();
        }
    }


    @Override
    public void onCheckNewVersionSuccess(UpgradeResultBean resultBean) {
        if (resultBean.isNeedUpgrade()) {
            showUpgradeDialog(resultBean.getPackageUrl());
        }
    }

    private void showUpgradeDialog(String apkUrl) {
        mUpgradeDialog = new UpgradeDialog(this, apkUrl);
        mUpgradeDialog.show();
    }

    /**
     * 在主页点击返回按钮，把当前app进程退到后台
     */
    @Override
    public void onBackPressed() {
        moveTaskToBack(false);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        LogUtil.d(TAG, "onNewIntent()");
        mIsStartHealth = false;
    }

    @Override
    public void onMessage(int code, String extInfo, String msg) {
        Log.d(TAG, "收到消息 code = " + code + " extInfo = " + extInfo + " msg = " + msg);
        MessageBean messageBean = new Gson().fromJson(msg, MessageBean.class);
        if (null != messageBean) {
            switch (messageBean.getMsgtype()) {
                case MessageBean.MSG_TYPE_INVITE:
                    showInviteDialog(messageBean);
                    launchToForeground();
                    break;
                case MessageBean.MSG_TYPE_REPLY:
                    if (messageBean.isResultAccept()) {
                        ToastUtil.showToast(messageBean.getNickname() + "同意加入通话");
                    } else {
                        ToastUtil.showToast(messageBean.getNickname() + "拒绝加入通话");
                    }
                    break;
                case MessageBean.MSG_TYPE_HANG_UP:
                    boolean needDismissDialog = dismissInviteDialog(messageBean.getId());
                    if (needDismissDialog) {
                        ToastUtil.showToast("对方已挂断");
                    }
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 把app唤醒到前台
     */
    private void launchToForeground() {
        //如果开启了"健康学堂"就需要重启MainActivity
        if (mIsStartHealth) {
            MainActivity.launch(this);
            return;
        }
        //如果app在后台就需要把它唤醒到前台
        ActivityManager am = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
        am.moveTaskToFront(getTaskId(), ActivityManager.MOVE_TASK_WITH_HOME);
    }

    @Override
    public void onStatusChange(String cid, int status, String extInfo) {

    }

}
